<?php

function params($string, $data) {
    $indexed = $data == array_values($data);
    foreach ($data as $k => $v) {
        if (is_string($v)) {
            $c = substr($v, 0, 1);
            if ($c <> '.' && $c <> '{') {
                $v = "\"$v\"";
            }
        }
        if ($indexed) {
            $string = preg_replace('/\?/', $v, $string, 1);
        } else {
            $string = str_replace($k, $v, $string);
        }
    }
    return $string;
}

require_once 'config.php';

//get shiftcode string from CRSHIFT.MEM file
$filename = $db_path . '\\' . $outlet_location . '\\crshift.mem';
if (!file_exists($filename)) {
    echo "ShiftCode file is not found. No POS transaction added! \nPlease check config file!";
    return;
}
$file = fopen($filename, 'r');
$filecontent = fread($file, filesize($filename));
$i = strpos($filecontent, 'CRSHIFTCODE');
if (fseek($file, $i + 11) == 0) {
    $shiftcode = fgets($file, 10);
}
fclose($file);

//    print_r($_POST);
$json = file_get_contents('php://input');
//return $json;

$vars = json_decode($json, true);
$waiter = $vars['WaiterID'];
$items = $vars['items'];
$tableno = $vars['tableno'];
$bar_receipt = '';

//$items = json_decode($json);
if (count($items) <= 0) {
    return 'No items in the cart.';
}
try {
    $db = new PDO("odbc:$odbc_name", '', '');

//    $db->query("SET NAMES 'utf8'");
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    error_log($e->getMessage());
    die("A database error was encountered, maybe ODBC name $odbc_name was not set in the OS yet. (in file: " . __FILE__ . ')');
}

try {
    //get next receipt number
    $query = "select * from tranno where tranno='a'";
    $stmt = $db->prepare($query);
    $stmt->execute();

    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    unset($stmt);

    $next_doc = $row['next_doc'];
    $doc_size = $row['doc_size'] - 1;

    //update receipt number to the next one
    $query = "update tranno set next_doc = next_doc + 1 where tranno='a'";
    $stmt = $db->prepare($query);
    $stmt->execute();
    unset($stmt);

    //create receipt string
    $fmtstr = sprintf('%%0%ds', $doc_size);
    $billno = sprintf($fmtstr, $next_doc);
    $sales = 'A' . $billno;
    $curdate = date('m/d/Y', time());
    $curtime = date('H:i:s', time());

    $mperiod = '';
//    $shiftcode = '201407051';
    $timelastor = time();
    $transact = 'H';
    $amount = 0;
    $svcamt = 0;
    $startid = $waiter;
    $bar_receipt .= "\x1b\x40";  //initialize printer
    $bar_receipt .= "\x1bM\x0";  //select font A
    $bar_receipt .= sprintf("Time: %s Table No.: %s\n" .
            "Receipt No.: %s\n" .
            "Waiter: %s\n" .
            "Items:\n", date('m/d/Y H:i:s'), $tableno, $sales, $waiter);

    $query = 'insert into sales1 ' .
            '(sales, date, time, mperiod, cashier, customer, shiftcode, terminal, slsgroup, ' .
            'timelastor, timepaym, transact, amount, amtpaid, prevpaid, remark1, svcamt, ' .
            'taxamt1, taxamt2, gstamt, zxtamount, zxsamount, zgtsvcamt, zstsvcamt, ' .
            'zgttaxamt1, zsttaxamt1, zgttaxamt2, zsttaxamt2, zgtgstamt, zxlineprt, ' .
            'grossamt, totlcost, ctrlkey, billno, waiter, tableno, pax, prevttl, ' .
            'prevgttl, prevbill, prevline, manager, entbal, rcpcnt, billcnt, print, ' .
            'discpcnt, taxincl, opentrack, rcppcnt, billpcnt, timeturn, doubdisc, ' .
            'card_no, card_type, card_name, ptsvalue, ptstotal, ptsexpire, rebateval, ' .
            'rebatettl, card_ver, rcpfooter1, rcpfooter2, netlive, pfactor, pfactdes, ' .
            'ptsamount, spendamt, taxinv, ttlpcnt, ttlpamt, ttlpid, rcppid, billpid, ' .
            'lupddate, lupdtime, paymtype, card_disc, startid, timevoid, taxinv1, ' .
            'taxinv2, ptsredeem, entflag) values ' .
            '(:sales, :date, :_time, :mperiod, :cashier, :customer, :shiftcode, ' .
            ':terminal, :slsgroup, :timelastor, :timepaym, :transact, :amount, ' .
            ':amtpaid, :prevpaid, :remark1, :svcamt, :taxamt1, :taxamt2, :gstamt, ' .
            ':zxtamount, :zxsamount, :zgtsvcamt, :zstsvcamt, :zgttaxamt1, ' .
            ':zsttaxamt1, :zgttaxamt2, :zsttaxamt2, :zgtgstamt, :zxlineprt, ' .
            ':grossamt, :totlcost, :ctrlkey, :billno, :waiter, :tableno, :pax, ' .
            ':prevttl, :prevgttl, :prevbill, :prevline, :manager, :entbal, :rcpcnt, ' .
            ':billcnt, :print, :discpcnt, :taxincl, :opentrack, :rcppcnt, :billpcnt, ' .
            ':timeturn, :doubdisc, :card_no, :card_type, :card_name, :ptsvalue, ' .
            ':ptstotal, :ptsexpire, :rebateval, :rebatettl, :card_ver, :rcpfooter1, ' .
            ':rcpfooter2, :netlive, :pfactor, :pfactdes, :ptsamount, :spendamt, ' .
            ':_taxinv, :ttlpcnt, :ttlpamt, :ttlpid, :rcppid, :billpid, :lupddate, ' .
            ':lupdtime, :paymtype, :card_disc, :startid, :timevoid, :taxinv1, ' .
            ':taxinv2, :ptsredeem, :entflag)';
    $sql_data = array(
        ':sales' => $sales,
        ':date' => '{' . $curdate . '}',
//        ':date' => $curdate,
        ':_time' => $curtime,
        ':mperiod' => $mperiod,
        ':cashier' => $waiter, //maybe differenct with waiter
        ':customer' => '',
        ':shiftcode' => $shiftcode, //don't know where it from yet
        ':terminal' => $terminal_name,
        ':slsgroup' => '',
        ':timelastor' => date('H:i:s', time()),
        ':timepaym' => '',
        ':transact' => 'H',
        ':amount' => $amount,
        ':amtpaid' => 0,
        ':prevpaid' => 0,
        ':remark1' => '',
        ':svcamt' => 0,
        ':taxamt1' => 0,
        ':taxamt2' => 0,
        ':gstamt' => 0,
        ':zxtamount' => $amount,
        ':zxsamount' => $amount,
        ':zgtsvcamt' => $amount,
        ':zstsvcamt' => 0,
        ':zgttaxamt1' => 0,
        ':zsttaxamt1' => 0,
        ':zgttaxamt2' => $amount,
        ':zsttaxamt2' => 0,
        ':zgtgstamt' => 0,
        ':zxlineprt' => 0,
        ':grossamt' => $amount,
        ':totlcost' => 0,
        ':ctrlkey' => '',
        ':billno' => $billno,
        ':waiter' => $waiter,
        ':tableno' => $tableno,
        ':pax' => 1,
        ':prevttl' => 0,
        ':prevgttl' => 0,
        ':prevbill' => '',
        ':prevline' => 0,
        ':manager' => '',
        ':entbal' => 0,
        ':rcpcnt' => 0,
        ':billcnt' => 0,
        ':print' => 0, //'.F.',
        ':discpcnt' => '',
        ':taxincl' => 0, //'.F.',
        ':opentrack' => '',
        ':rcppcnt' => 0,
        ':billpcnt' => 0,
        ':timeturn' => date('H:i', time()),
        ':doubdisc' => 0, //'.F.',
        ':card_no' => '',
        ':card_type' => '',
        ':card_name' => '',
        ':ptsvalue' => 0,
        ':ptstotal' => 0,
        ':ptsexpire' => '{}',
        ':rebateval' => 0,
        ':rebatettl' => 0,
        ':card_ver' => 0,
        ':rcpfooter1' => '',
        ':rcpfooter2' => '',
        ':netlive' => 0, //'.F.',
        ':pfactor' => 0,
        ':pfactdes' => '',
        ':ptsamount' => 0,
        ':spendamt' => 0,
        ':_taxinv' => '',
        ':ttlpcnt' => 0,
        ':ttlpamt' => 0,
        ':ttlpid' => '',
        ':rcppid' => '',
        ':billpid' => '',
        ':lupddate' => '{' . date('m/d/Y', time()) . '}',
        ':lupdtime' => date('H:i:s', time()),
        ':paymtype' => '',
        ':card_disc' => 0,
        ':startid' => $waiter,
        ':timevoid' => '',
        ':taxinv1' => '',
        ':taxinv2' => '',
        ':ptsredeem' => 0,
        ':entflag' => 0 //'.F.'
    );
    $sql = params($query, $sql_data);
    $stmt = $db->prepare($sql);
    $stmt->execute();
    /*    $stmt = $db->prepare($query);
      $stmt->execute($sql_data); */
    unset($stmt);

    //insert all items in the table sales2
    $query = 'insert into sales2 (sales, item_no, stock, location, descrip1, ' .
            'quantity, uom, price, discount, discpcnt, amount, netamt, totlcost, ' .
            'svcamt, taxamt1, taxamt2, gstamt, svcind, tax1ind, tax2ind, gstind, ' .
            'discind, shiftcode, shifttime, terminal, salesman, prevorder, ' .
            'item_void, authid, crposted, seatno, fireline, slsgroup, ctrlkey, ' .
            'pricelevel, manager, netdisc, netdiscttl, taxpcnt, voucher_id, tagnos, ' .
            'tagprinted, disclock, voidrmk, remindcnt, serialno, checkin, checkout, ' .
            'kpremincnt, bk_refid, bk_session, bk_name, bk_date, bk_start, bk_end, ' .
            'bk_rideloc, zeroprice, modflag, setitem_no, trfsales, discttl, ' .
            'trftableno) values (' .
            ':_sales, :item_no, :stock, :location, :descrip1, :quantity, :uom, ' .
            ':_price, :discount, :discpcnt, :amount, :netamt, :totlcost, :svcamt, ' .
            ':taxamt1, :taxamt2, :gstamt, :svcind, :tax1ind, :tax2ind, :gstind, ' .
            ':discind, :shiftcode, :shifttime, :terminal, :salesman, :prevorder, ' .
            ':item_void, :authid, :crposted, :seatno, :fireline, :slsgroup, ' .
            ':ctrlkey, :pricelevel, :manager, :_netdisc, :netdiscttl, :taxpcnt, ' .
            ':voucher_id, :tagnos, :tagprinted, :disclock, :voidrmk, :remindcnt, ' .
            ':serialno, :checkin, :checkout, :kpremincnt, :bk_refid, :bk_session, ' .
            ':bk_name, :bk_date, :bk_start, :bk_end, :bk_rideloc, :zeroprice, ' .
            ':modflag, :setitem_no, :trfsales, :discttl, :trftableno)';

    //insert item into sales2 table
    $i = 0; //sales2 line No.
    $total_amount = 0;
    foreach ($items as $item) {
        $i = $i + 1;
        //get stock master of the $item
        $q = 'select * from stock where stock = :stock';
        $s = $db->prepare($q);
        if ($s->execute(array(':stock' => $item['stock']))) {
            $stock_master = $s->fetch(PDO::FETCH_ASSOC);
        }
        unset($s);

        //get stock's dept
        $q = 'select * from dept where dept = :dept';
        $s = $db->prepare($q);
        if ($s->execute(array(':dept' => $stock_master['group']))) {
            $stock_dept = $s->fetch(PDO::FETCH_ASSOC);
        }
        unset($s);

        $item_amount = $item['price'];
        $total_amount = $total_amount + $item_amount;

        $sql_data = array(
            ':_sales' => $sales,
            ':item_no' => strval($i),
            ':stock' => $item['stock'],
            ':location' => $location,
            ':descrip1' => $item['name'],
            ':quantity' => 1,
            ':uom' => $stock_master['uom'],
            ':_price' => $item['price'],
            ':discount' => 0,
            ':discpcnt' => '',
            ':amount' => $item_amount,
            ':netamt' => $item_amount,
            ':totlcost' => 0,
            ':svcamt' => 0,
            ':taxamt1' => 0,
            ':taxamt2' => 0,
            ':gstamt' => 0,
            ':svcind' => intval($stock_dept['service']), //boolean: 0 = .F., 1 = .T.
            ':tax1ind' => intval($stock_dept['tax1']), //boolean: 0 = .F., 1 = .T.
            ':tax2ind' => intval($stock_dept['tax2']), //boolean: 0 = .F., 1 = .T.
            ':gstind' => intval($stock_dept['gst']), //boolean: 0 = .F., 1 = .T.
            ':discind' => intval($stock_dept['discount']), //boolean: 0 = .F., 1 = .T.
            ':shiftcode' => $shiftcode, //don't know where get it from
            ':shifttime' => date('H:i:s', time()),
            ':terminal' => $terminal_name,
            ':salesman' => $waiter,
            ':prevorder' => 1, //'.T.',
            ':item_void' => '',
            ':authid' => $waiter,
            ':crposted' => 0, //'.F.',
            ':seatno' => '',
            ':fireline' => '',
            ':slsgroup' => '',
            ':ctrlkey' => 'X',
            ':pricelevel' => '',
            ':manager' => '',
            ':_netdisc' => 0,
            ':netdiscttl' => 0,
            ':taxpcnt' => 0,
            ':voucher_id' => '',
            ':tagnos' => '',
            ':tagprinted' => 0, //'.F.',
            ':disclock' => 0, //'.F.',
            ':voidrmk' => '',
            ':remindcnt' => 0,
            ':serialno' => '',
            ':checkin' => '{}',
            ':checkout' => '{}',
            ':kpremincnt' => 0,
            ':bk_refid' => '',
            ':bk_session' => '',
            ':bk_name' => '',
            ':bk_date' => '{}',
            ':bk_start' => '',
            ':bk_end' => '',
            ':bk_rideloc' => '',
            ':zeroprice' => intval($stock_master['zeroprice']), //'.F.',
            ':modflag' => 0, //'.F.',
            ':setitem_no' => '',
            ':trfsales' => '',
            ':discttl' => 0,
            ':trftableno' => ''
        );
        $sql = params($query, $sql_data);
        $stmt = $db->prepare($sql);
        $stmt->execute();
        /*        $stmt = $db->prepare($query);
          $stmt->execute($sql_data); */
        unset($stmt);
    }

    $curtime = date('H:i:s', time());
    $query = "update sales1 set amount = $total_amount, "
            . "zxtamount = $total_amount, "
            . "zxsamount = $total_amount, "
            . "zgtsvcamt = $total_amount, "
            . "zgttaxamt2 = $total_amount, "
            . "grossamt = $total_amount, "
            . "timelastor = '$curtime', "
            . "lupdtime = '$curtime' "
            . "where sales='$sales'";
    $stmt = $db->prepare($query);
    $stmt->execute();
    unset($stmt);
	
	//try to update table no. for each web order
	$query = "update tableno set status='Food Ordered' where tableno.tableno='$tableno'";
    $stmt = $db->prepare($query);
    $stmt->execute();
    unset($stmt);

    $bar_receipt .= "\x1d!\x11"; //turn on double height mode
    $bar_receipt .= "\x1bG\x1"; //turn on dark mode
    $aggregated_items = array();
    foreach ($items as $item) {
        if (!empty($aggregated_items[$item['stock']])) {
            $aggregated_items[$item['stock']]['qty'] += 1;
        } else {
            $aggregated_items[$item['stock']]['qty'] = 1;
            $aggregated_items[$item['stock']]['name'] = $item['name'];
        }
    }
    foreach ($aggregated_items as $item) {
        $bar_receipt .= sprintf("%s  x%d\n", $item['name'], $item['qty']);
    }
    $bar_receipt .= "\x1bG\x0"; //turn on double height mode
    $bar_receipt .= "\x1d!\x0"; //turn off double height mode
    $bar_receipt .= "\n\n============== END ==============\n";
    $bar_receipt .= "\x1dV\x42\x0"; //feed paper and cut
    //print to bar receipt printer

    //print mether 1:
    $fp = fsockopen($bar_printer1_ip, 9100, $errno, $errstr, 10);
    if (!$fp) {
        echo "$errstr ($errno)<br />\n";
    } else {
        fwrite($fp, $bar_receipt);
        fclose($fp);
    }
    //print mether 2
/*    if ($bar_printer1 = printer_open($bar_printer1_name)) {
        printer_set_option($bar_printer1, PRINTER_MODE, 'text');
        printer_write($bar_printer1, $bar_receipt);
        printer_close($bar_printer1);
    }
    if ($bar_printer2 = printer_open($bar_printer2_name)) {
        printer_set_option($bar_printer2, PRINTER_MODE, 'text');
        printer_write($bar_printer2, $bar_receipt);
        printer_close($bar_printer2);
    }*/
} catch (PDOException $e) {
    print $e->getMessage();
}
unset($db);
unset($stmt);
unset($s);

//return receipt number
echo 'Your receipt No. is ' . $sales . ' for table No. ' . $tableno;
?>